/*
 * Copyright 2018 Zhenjie Yan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yanzhenjie.andserver.controller;

import com.yanzhenjie.andserver.MyApplication;
import com.yanzhenjie.andserver.annotation.*;
import com.yanzhenjie.andserver.component.LoginInterceptor;
import com.yanzhenjie.andserver.event.MessageEvent;
import com.yanzhenjie.andserver.framework.body.FileBody;
import com.yanzhenjie.andserver.framework.body.StreamBody;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.http.cookie.Cookie;
import com.yanzhenjie.andserver.http.multipart.MultipartFile;
import com.yanzhenjie.andserver.http.session.Session;

import com.yanzhenjie.andserver.model.UserInfo;
import com.yanzhenjie.andserver.slice.MainAbilitySlice;
import com.yanzhenjie.andserver.util.FileUtils;
import com.yanzhenjie.andserver.util.Logger;
import com.yanzhenjie.andserver.util.MediaType;
import ohos.agp.window.dialog.ToastDialog;
import org.greenrobot.eventbus.EventBus;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by Zhenjie Yan on 2018/6/9.
 */
@RestController
@RequestMapping(path = "/user")
class TestController {

    @CrossOrigin(
            methods = {RequestMethod.POST, RequestMethod.GET}
    )
    @RequestMapping(
            path = "/get/{userId}",
            method = {RequestMethod.PUT, RequestMethod.POST, RequestMethod.GET},
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    String info(@PathVariable(name = "userId") String userId) {
        return userId;
    }

    @PutMapping(path = "/get/{userId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    String modify(@PathVariable("userId") String userId, @RequestParam(name = "sex") String sex,
                  @RequestParam(name = "age") int age) {
        String message = "The userId is %1$s, and the sex is %2$s, and the age is %3$d.";
        return String.format(Locale.US, message, userId, sex, age);
    }

    @PostMapping(path = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    String login(HttpRequest request, HttpResponse response, @RequestParam(name = "account") String account,
                 @RequestParam(name = "password") String password) {
        Cookie cookie = new Cookie("account", account + "=" + password);
        response.addCookie(cookie);
        System.out.println("jk---->login: Login successful");
        response.sendRedirect("/web/uploadindex");
        return "/uploadindex";
    }

    @Addition(stringType = "login", booleanType = true)
    @GetMapping(path = "/userInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    UserInfo userInfo(@CookieValue("account") String account) {
        Logger.i("Account: " + account);
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("123");
        userInfo.setUserName("AndServer");
        return userInfo;
    }

    @PostMapping(path = "/upload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    String upload(@RequestParam(name = "avatar") MultipartFile file) throws IOException {
        File localFile = FileUtils.createRandomFile(file);
        file.transferTo(localFile);
        EventBus.getDefault().post(new MessageEvent());
        new ToastDialog(MyApplication.getInstance().getContext()).setText("上传成功，请刷新网页端").show();
        return localFile.getCanonicalPath();
    }

    @PostMapping(path = "/delete", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    String delete(@RequestParam(name = "name") @RequestBody String name) throws IOException {
        File file = new File(new MainAbilitySlice().getPath() + "/" + name);
        boolean delete = file.delete();
        String s = "";
        if (delete) {
            s = "删除文件“" + name + "”成功！";
        } else {
            s = "删除文件“" + name + "”失败！";
        }
        System.out.println("delete-");
        EventBus.getDefault().post(new MessageEvent());
        return s;
    }

    @RequestMapping(
            path = "/fileList",
            method = {RequestMethod.PUT, RequestMethod.POST, RequestMethod.GET},
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    com.yanzhenjie.andserver.http.ResponseBody download(HttpRequest request, HttpResponse response) throws IOException {
        String uri = request.getURI();
        String fileName = uri.substring(uri.lastIndexOf("=") + 1);
//        String fileName=request.getParameter("name");
        String decode = URLDecoder.decode(fileName, "utf-8");
        System.out.println("fileName：" + fileName);

        System.out.println("请求的URI是：" + uri);
        System.out.println("文件名是：" + fileName);
        System.out.println("解码后的文件名：" + decode);
        File fileEntity = new File(new MainAbilitySlice().getPath() + "/" + fileName);
        if (fileEntity.exists()) {
            System.out.println("docdocdoc：" + "存在" + fileEntity.length());

        } else {
            System.out.println("docdocdoc：" + "11223存在");
        }
        response.setHeader("contentType", "application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));//不设置这个就没有下载的效果，举例：如果是txt文件，浏览器就会直接展示文字，而不是下载
        response.setBody(new StreamBody(FileUtils.fileToinputstream(fileEntity)));
        InputStream fis = null;
        try {
            //以流的形式下载文件
            fis = new BufferedInputStream(new FileInputStream(new MainAbilitySlice().getPath() + "/" + fileName));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

        } catch (FileNotFoundException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            e.fillInStackTrace();
        } finally {
            fis = null;
            fis.close();

        }
        return new StreamBody(FileUtils.fileToinputstream(fileEntity));
//        FileEntity fileEntity=new FileEntity(new File(MainAbilitySlice.path + "/" + name));
//        response.ge
//        response.get
//        response.setHeader("Content-Disposition", "attachment;filename="+name);//不设置这个就没有下载的效果，举例：如果是txt文件，浏览器就会直接展示文字，而不是下载
//        response.setEntity(fileEntity);
    }

    //        @PostMapping(path = "/fileDownload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    String filelist(@RequestParam(name = "avatar") MultipartFile file) throws IOException {
//        File localFile = FileUtils.createRandomFile(file);
//        file.transferTo(localFile);
//        System.out.println("jk---->upload: upload successful---"+file.getFilename()+"-----"+localFile.getAbsolutePath());
//
//        return localFile.getAbsolutePath();
//    }
    @GetMapping(path = "/consume", consumes = {"application/json", "!application/xml"})
    String consume() {
        return "Consume is successful";
    }

    @GetMapping(path = "/produce", produces = {"application/json; charset=utf-8"})
    String produce() {
        return "Produce is successful";
    }

    @GetMapping(path = "/include", params = {"name=123"})
    String include(@RequestParam(name = "name") String name) {
        return name;
    }

    @GetMapping(path = "/exclude", params = "name!=123")
    String exclude() {
        return "Exclude is successful.";
    }

    @GetMapping(path = {"/mustKey", "/getName"}, params = "name")
    String getMustKey(@RequestParam(name = "name") String name) {
        return name;
    }

    @PostMapping(path = {"/mustKey", "/postName"}, params = "name")
    String postMustKey(@RequestParam(name = "name") String name) {
        return name;
    }

    @GetMapping(path = "/noName", params = "!name")
    String noName() {
        return "NoName is successful.";
    }

    @PostMapping(path = "/formPart")
    UserInfo forPart(@FormPart(name = "user") UserInfo userInfo) {
        return userInfo;
    }

    @PostMapping(path = "/jsonBody")
    UserInfo jsonBody(@RequestBody UserInfo userInfo) {
        return userInfo;
    }

    @PostMapping(path = "/listBody")
    List<UserInfo> jsonBody() {
        System.out.println("xxxxx-----");
        boolean status = true;
        String errMsg = "";
        String note = "";
        List<UserInfo> myFileList = new ArrayList<>();
        MainAbilitySlice mainAbilitySlice = new MainAbilitySlice();
        String fileDirectory = mainAbilitySlice.getPath();
        File file = new File(fileDirectory);
        File[] files = file.listFiles();
        if (files == null) {
            status = false;
            errMsg = "无法获取服务器中的文件，请确认服务器已经授予读写权限！";
        } else if (files.length != 0) {
            Arrays.sort(files, new Comparator<File>() {//按文件的修改日期递增排序
                public int compare(File f1, File f2) {
                    long diff = f1.lastModified() - f2.lastModified();
                    if (diff > 0)
                        return 1;
                    else if (diff == 0)
                        return 0;
                    else
                        return -1;
                }

//                public boolean equals(Object obj) {
//                    return true;
//                }
            });


            for (int i = 0; i < files.length; i++) {
                File fi = files[i];
                String name = fi.getName();
                long length = fi.length();
                double len = (double) length / 1024;//kb
                boolean directory = fi.isDirectory();
                UserInfo myFile = new UserInfo(name, len, directory);
                myFileList.add(myFile);
            }
        } else {

        }

        return myFileList;
    }
}